/**
 * Created by Mark_ren on 2016/11/28.
 * 苟富贵,無相忘
 */
var express = require('express');
var moment = require("moment");
var router = express.Router();
var co = require('co');
var seqModule = require('./createModules');
var seq = new seqModule();
var fs = require('fs');
var nodeExcel = require('excel-export');

var formidable = require('formidable');
var getIP = require('./getIP');

router.get('/getMemberPages', function (req, res, next) {
    co(function () {
        var page = parseInt(req.query.page);
        var params = {};
        var paramT = {};
        var paramD = [];
        var include = [{ model: seq.wxUsersModule }];
        paramT.include = include;
        //根据id
        if (req.query.id != undefined) {
            params["id"] = req.query.id;
        }
        if (req.query.openId != undefined) {
            params["openId"] = req.query.openId;
        }
        //模糊查询
        if (req.query.name != undefined) {
            params["name"] = { "$like": "%" + req.query.name + "%" };

        }
        if (req.query.tel != undefined) {
            params["tel"] = { "$like": "%" + req.query.tel + "%" };

        }
        if (req.query.pTitle != undefined) {
            params["$or"] = { "name": { "$like": "%" + req.query.pTitle + "%" }, "tel": { "$like": "%" + req.query.pTitle + "%" } };
        }
        if (req.query.type != undefined) {
            //params["type"]=parseInt(req.query.type);

            if (req.query.type == 0) {
                paramD = [{ "hospitalName": { "$ne": "天普" } }, { "hospitalName": { "$ne": "诺联" } }];
                params["$and"] = paramD;
            } else {
                paramD = [{ "hospitalName": "天普" }, { "hospitalName": "诺联" }];
                params["$or"] = paramD;
            }

        }
        if (req.query.province != undefined) {
            params["province"] = { "$like": "%" + req.query.province + "%" };

        } if (req.query.city != undefined) {
            params["city"] = { "$like": "%" + req.query.city + "%" };

        }
        if (req.query.cTitle != undefined) {
            params["$or"] = { "province": { "$like": "%" + req.query.cTitle + "%" }, "city": { "$like": "%" + req.query.cTitle + "%" } };
        }
        if (req.query.hospitalName != undefined) {
            params["hospitalName"] = { "$like": "%" + req.query.hospitalName + "%" };

        }
        if (req.query.hospitalOffices != undefined) {
            params["hospitalOffices"] = { "$like": "%" + req.query.hospitalOffices + "%" };

        }
        if (req.query.wxTitle != undefined) {
            params["$or"] = { "name": { "$like": "%" + decodeURI(req.query.wxTitle) + "%" }, "hospitalName": { "$like": "%" + decodeURI(req.query.wxTitle) + "%" }, "hospitalOffices": { "$like": "%" + decodeURI(req.query.wxTitle) + "%" } };
        }
        if (req.query.filed1 != undefined) {
            params["filed1"] = { "$like": "%" + req.query.filed1 + "%" };

        }
        if (req.query.filed2 != undefined) {
            params["filed2"] = { "$like": "%" + req.query.filed2 + "%" };

        }
        if (req.query.filed3 != undefined) {
            params["filed3"] = { "$like": "%" + req.query.filed3 + "%" };

        }
        if (req.query.filed4 != undefined) {
            params["filed4"] = { "$like": "%" + req.query.filed4 + "%" };

        }
        if (req.query.filed5 != undefined) {
            params["filed5"] = { "$like": "%" + req.query.filed5 + "%" };

        }
        if (req.query.filed8 != undefined) {
            params["filed8"] = req.query.filed8;

        }
        paramT["where"] = params;
        paramT["order"] = [["createTime", 'DESC']];
        if (req.query.page != undefined && req.query.rows != undefined) {
            paramT["offset"] = parseInt(req.query.page);
            paramT["limit"] = parseInt(req.query.rows);
        }
        seq.memberModule.findAndCountAll(paramT).then(function (result) {
            res.json({ "success": true, "page": page, "total": result.count, "result": result.rows });
        });
    }).catch(function (e) {
        res.json({ 'success': false, 'msg': '查询失败' });
        console.log(e);
    })
});


//查询用户信息/分页
router.get('/getmemberPage', function (req, res, next) {
    co(function () {
        var page = parseInt(req.query.page);
        var params = {};
        var paramT = {};
        var include = [{ model: seq.memberRespresentModule }];
        paramT.include = include;
        //根据id
        if (req.query.id != undefined) {
            params["id"] = req.query.id;
        }
        //模糊查询
        if (req.query.name != undefined) {
            params["name"] = { "$like": "%" + req.query.name + "%" };

        }
        if (req.query.tel != undefined) {
            params["tel"] = { "$like": "%" + req.query.tel + "%" };

        }
        if (req.query.type != undefined) {
            if (req.query.type == 0) {
                paramD = [{ "hospitalName": { "$ne": "天普" } }, { "hospitalName": { "$ne": "诺联" } }];
                params["$or"] = [{ "$and": paramD }, { "hospitalName": null }, { "hospitalName": "" }]

            } else {
                paramD = [{ "hospitalName": "天普" }, { "hospitalName": "诺联" }];
                params["$or"] = paramD;
            }

        }
        if (req.query.province != undefined) {
            params["province"] = { "$like": "%" + req.query.province + "%" };

        } if (req.query.city != undefined) {
            params["city"] = { "$like": "%" + req.query.city + "%" };

        }
        if (req.query.hospitalName != undefined) {
            params["hospitalName"] = { "$like": "%" + req.query.hospitalName + "%" };

        }
        if (req.query.hospitalOffices != undefined) {
            params["hospitalOffices"] = { "$like": "%" + req.query.hospitalOffices + "%" };

        }
        if (req.query.filed1 != undefined) {
            params["filed1"] = { "$like": "%" + req.query.filed1 + "%" };

        }
        if (req.query.filed2 != undefined) {
            params["filed2"] = { "$like": "%" + req.query.filed2 + "%" };

        }
        if (req.query.filed3 != undefined) {
            params["filed3"] = { "$like": "%" + req.query.filed3 + "%" };

        }
        if (req.query.filed4 != undefined) {
            params["filed4"] = { "$like": "%" + req.query.filed4 + "%" };

        }
        if (req.query.filed5 != undefined) {
            params["filed5"] = { "$like": "%" + req.query.filed5 + "%" };

        }
        if (req.query.startTime != undefined && req.query.endTime != undefined) {
            params["createTime"] = { "$gte": req.query.startTime, "$lte": req.query.endTime };
        } else if (req.query.startTime != undefined && req.query.endTime == undefined) {
            params["createTime"] = { "$gte": req.query.startTime };
        } else if (req.query.startTime == undefined && req.query.endTime != undefined) {
            params["createTime"] = { "$lte": req.query.endTime };
        }

        paramT["where"] = params;
        paramT["order"] = [["createTime", 'DESC']];
        if (req.query.page != undefined && req.query.rows != undefined) {
            paramT["offset"] = parseInt(req.query.page);
            paramT["limit"] = parseInt(req.query.rows);
        }
        seq.memberModule.findAndCountAll(paramT).then(function (result) {
            res.json({ "success": true, "page": page, "total": result.count, "result": result.rows });
        });
    }).catch(function (e) {
        res.json({ 'success': false, 'msg': '查询失败' });
        console.log(e);
    })
});

//会员导出
router.get('/getmemberExcel', function (req, res, next) {
    co(function () {
        var params = {};
        var paramT = {};
		 var include = [{ model: seq.memberRespresentModule,attributes:['name'] }];
        paramT.include = include;
        //根据id
        if (req.query.id != undefined) {
            params["id"] = req.query.id;
        }
        //模糊查询
        if (req.query.name != undefined) {
            params["name"] = { "$like": "%" + req.query.name + "%" };

        }
        if (req.query.tel != undefined) {
            params["tel"] = { "$like": "%" + req.query.tel + "%" };

        }
        if (req.query.type != undefined) {
            if (req.query.type == 0) {
                paramD = [{ "hospitalName": { "$ne": "天普" } }, { "hospitalName": { "$ne": "诺联" } }];
                params["$or"] = [{ "$and": paramD }, { "hospitalName": null }, { "hospitalName": "" }]

            } else {
                paramD = [{ "hospitalName": "天普" }, { "hospitalName": "诺联" }];
                params["$or"] = paramD;
            }

        }
        if (req.query.province != undefined) {
            params["province"] = { "$like": "%" + req.query.province + "%" };

        }
        if (req.query.city != undefined) {
            params["city"] = { "$like": "%" + req.query.city + "%" };

        }
        if (req.query.hospitalName != undefined && req.query.hospitalName != "") {
            params["hospitalName"] = { "$like": "%" + req.query.hospitalName + "%" };

        }
        if (req.query.hospitalOffices != undefined) {
            params["hospitalOffices"] = { "$like": "%" + req.query.hospitalOffices + "%" };

        }
        if (req.query.filed1 != undefined) {
            params["filed1"] = { "$like": "%" + req.query.filed1 + "%" };

        }
        if (req.query.filed2 != undefined) {
            params["filed2"] = { "$like": "%" + req.query.filed2 + "%" };

        }
        if (req.query.filed3 != undefined) {
            params["filed3"] = { "$like": "%" + req.query.filed3 + "%" };

        }
        if (req.query.filed4 != undefined) {
            params["filed4"] = { "$like": "%" + req.query.filed4 + "%" };

        }
        if (req.query.filed5 != undefined) {
            params["filed5"] = { "$like": "%" + req.query.filed5 + "%" };

        }
        if (req.query.startTime != undefined && req.query.endTime != undefined) {
            params["createTime"] = { "$gte": req.query.startTime, "$lte": req.query.endTime };
        } else if (req.query.startTime != undefined && req.query.endTime == undefined) {
            params["createTime"] = { "$gte": req.query.startTime };
        } else if (req.query.startTime == undefined && req.query.endTime != undefined) {
            params["createTime"] = { "$lte": req.query.endTime };
        }
        paramT["where"] = params;
        paramT["order"] = [["createTime", 'DESC']];
        seq.memberModule.findAndCountAll(paramT).then(function (result) {
            var trasations = [];
            var conf = {};
            conf.stylesXmlFile = "styles.xml";

            trasations = result.rows;
            conf.name = "member";
            var vac = new Array();
            //设置表头
            conf.cols = [
                {
                    caption: '姓名',
                    type: 'string',
                    width: 10.6
                },
                {
                    caption: '手机号',
                    type: 'string',
                    width: 28
                }, {
                    caption: '省/市',
                    type: 'string',
                    width: 10
                },
                {
                    caption: '医院',
                    type: 'string',
                    width: 10
                },
                {
                    caption: '科室',
                    type: 'string',
                    width: 10
                },
                {
                    caption: '囯区',
                    type: 'string',
                    width: 10
                },
                {
                    caption: '大区',
                    type: 'string',
                    width: 10
                },
                {
                    caption: '地区',
                    type: 'string',
                    width: 10
                },
                {
                    caption: '产品',
                    type: 'string',
                    width: 10
                },
                {
                    caption: 'TP编码',
                    type: 'string',
                    width: 10
                },
                {
                    caption: '注册时间',
                    type: 'string',
                    width: 10
                },
				  {
                    caption: '代表姓名',
                    type: 'string',
                    width: 10
                },{
                    caption: '积分',
                    type: 'string',
                    width: 10
                },{
                    caption: '城市',
                    type: 'string',
                    width: 10
                },{
                    caption: '邮箱',
                    type: 'string',
                    width: 10
                },{
                    caption: '职称',
                    type: 'string',
                    width: 10
                }
            ];

            for (var i = 0; i < trasations.length; i++) {
                var temp = new Array();
                temp[0] = trasations[i].name + "";
                temp[1] = trasations[i].tel + "";
                temp[2] = trasations[i].province +"";
                temp[3] = trasations[i].hospitalName + "";
                temp[4] = trasations[i].hospitalOffices + "";
                temp[5] = trasations[i].filed1 + "";
                temp[6] = trasations[i].filed2 + "";
                temp[7] = trasations[i].filed3 + "";
                temp[8] = trasations[i].filed4 + "";
                temp[9] = trasations[i].filed5 + "";
                temp[10] = trasations[i].createTime + "";
				var name = "";
				if(trasations[i].memberRespresent != null && trasations[i].memberRespresent != undefined){
					name = trasations[i].memberRespresent.name;
				}
				 temp[11] = name + "";
				  temp[12] = trasations[i].filed10 + "";
				  temp[13] = trasations[i].city + "";
				   temp[14] = trasations[i].email + "";
				   temp[15] = trasations[i].jobTitle + "";

                //temp[10] = (trasations[i].state) == "0"?"未付款或未持久化":"已付款或已持久化";
                vac.push(temp);
            };


            conf.rows = vac;//conf.rows只接受数组
            var result = nodeExcel.execute(conf);
            res.setHeader('Content-Type', 'application/vnd.openxmlformats');
            res.setHeader("Content-Disposition", "attachment; filename=" + "member.xlsx");
            res.end(result, 'binary');
        });
    }).catch(function (e) {
        res.json({ 'success': false, 'msg': '查询失败' });
        console.log(e);
    })
});
//修改用户信息
router.get('/updmember', function (req, res, next) {
    co(function () {
        var params = {};
        var paramT = {};
        var paramU = {};
        //根据id
        if (req.query.id != undefined) {
            paramU["id"] = req.query.id;
        }
        //模糊查询
        if (req.query.name != undefined) {
            params["name"] = req.query.name;

        }
        if (req.query.tel != undefined) {
            params["tel"] = req.query.tel;

        }
        if (req.query.province != undefined) {
            params["province"] = req.query.province;

        }
        if (req.query.type != undefined) {
            params["type"] = parseInt(req.query.type);

        }
        if (req.query.hospitalName != undefined) {
            params["hospitalName"] = req.query.hospitalName;

        }
        if (req.query.hospitalOffices != undefined) {
            params["hospitalOffices"] = req.query.hospitalOffices;

        }
        if (req.query.filed1 != undefined) {
            params["filed1"] = req.query.filed1;

        }
        if (req.query.filed2 != undefined) {
            params["filed2"] = req.query.filed2;

        }
        if (req.query.filed3 != undefined) {
            params["filed3"] = req.query.filed3;

        }
        if (req.query.filed4 != undefined) {
            params["filed4"] = req.query.filed4;
        }
        if (req.query.filed5 != undefined) {
            params["filed5"] = req.query.filed5;

        }
        if (req.query.filed8 != undefined) {
            params["filed8"] = req.query.filed8;

        }
        paramT["where"] = paramU;
        seq.memberModule.update(params, paramT).then(function (results) {
            res.json({ "success": true, "msg": "修改成功", "rows": results });
        });
    }).catch(function (e) {
        res.json({ 'success': false, 'msg': '查询失败' });
        console.log(e);
    })
});

//修改用户信息
router.post('/updateMemberPost', function (req, res, next) {
    co(function () {
        if (req.method.toLowerCase() == 'post') {
            // parse a file upload
            var form = new formidable.IncomingForm();
            //files = [],
            //fields = [];

            form.type = true;
            form.on("progress", function (bytesReceived, bytesExpected) {
                console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                // 百分比
                var percent = Math.round(bytesReceived / bytesExpected * 100);
                console.log("percent:" + percent + "%");
                // 存入
                //sessions.setSession(req,res,opts);
            });
            form.parse(req, function (err, fields, files) {
                // res.render('index', { paths: [files.upload.name] });
                var paramT = {};
                var params = {};
                paramT.where = { "id": fields.id };
                delete fields.id;
                console.log(JSON.stringify(fields));

                if (fields.name != undefined && fields.name != "") {
                    params["name"] = fields.name;

                }
                if (fields.tel != undefined && fields.tel != "") {
                    params["tel"] = fields.tel;

                }
                if (fields.province != undefined && fields.province != "") {
                    params["province"] = fields.province;

                }
                if (fields.city != undefined && fields.city != "") {
                    params["city"] = fields.city;

                }
                if (fields.hospitalName != undefined && fields.hospitalName != "") {
                    params["hospitalName"] = fields.hospitalName;

                }
                if (fields.hospitalOffices != undefined && fields.hospitalOffices != "") {
                    params["hospitalOffices"] = fields.hospitalOffices;

                }
                if (fields.filed1 != undefined && fields.filed1 != "") {
                    params["filed1"] = fields.filed1;

                }
                if (fields.filed2 != undefined && fields.filed2 != "") {
                    params["filed2"] = fields.filed2;

                }
                if (fields.filed3 != undefined && fields.filed3 != "") {
                    params["filed3"] = fields.filed3;

                }
                if (fields.filed4 != undefined && fields.filed4 != "") {
                    params["filed4"] = fields.filed4;
                }
                if (fields.filed5 != undefined && fields.filed5 != "") {
                    params["filed5"] = fields.filed5;

                }
                seq.memberModule.update(params, paramT).then(function (results) {
                    if (parseInt(fields.type) == 0) {
                        res.redirect(getIP + 'member/memberList.html');
                    } else {
                        res.redirect(getIP + 'member/memberOtherList.html');
                    }

                });


            });
        }
    }).catch(function (e) {
        res.json({ 'success': false, 'msg': '查询失败' });
        console.log(e);
    })
});

router.get('/unBindRespresent', function (req, res, next) {
    co(function () {
        var paramU = {};
        var paramP = {};
        var params = req.query.params;
        var filed8 = req.query.filed8;
        paramU.filed8 = filed8;
        var arr = params.split(",");
        var paramT = [arr];
        paramP.where = { "id": paramT };
        seq.memberModule.update(paramU, paramP).then(function (results) {
            res.json({ "success": true, "msg": "解绑成功", "rows": results });
        });
    }).catch(function (e) {
        res.json({ 'success': false, 'msg': '解绑失败' });
        console.log(e);
    })
});


module.exports = router;